<template>
  <div class="page-main">
    <query-page
      ref="queryPageRef"
      v-model:selectedKeys="selectedKeys"
      :form-component-config="formComponentConfig"
      :form-render-config="formRenderConfig"
      :form-render-keys="formRenderKeys"
      :table-component-config="tableComponentConfig"
      :table-render-config="tableRenderConfig"
      :table-render-keys="tableRenderKeys"
      :loading="isLoading"
      :data="renderData"
      :total="total"
      row-selection-type="checkbox"
      @selection-change="selectionChange"
      @query-data="getData"
    >
      <template #container-side>
        <a-space>
          <a-button
            v-permission="['procurement:plan-list:selectPlanListByPage']"
            type="primary"
            @click="newlyIncreased"
            >新增</a-button
          >
          <a-button
            v-permission="[
              'procurement:plan-list-change:deletePlanListChangeByIds',
            ]"
            :disabled="!selectedKeys.length"
            @click="delDate"
            >删除</a-button
          >

          <a-button
            v-permission="[
              'procurement:plan-list-change:batchUpdatePlanListChangeStatus2',
            ]"
            :disabled="!selectedKeys.length"
            @click="confirm"
            >确认</a-button
          >
          <a-button
            v-permission="[
              'procurement:plan-list-change:batchUpdatePlanListChangeStatus3',
            ]"
            :disabled="!selectedKeys.length"
            @click="SubmitExamine"
            >提交审批</a-button
          >
          <a-button
            v-permission="[
              'procurement:plan-list-change:batchUpdatePlanListChangeStatus',
            ]"
            :disabled="!selectedKeys.length"
            @click="send"
            >退回</a-button
          >
        </a-space>
      </template>
      <!-- ("单据状态 0-编制中,5-确认退回，10-已确认，15-审批中；20-审核通过；25-审核拒绝；30-已贯彻；35-贯彻撤销")
     changeStatus; -->
      <template #operate="{ record }">
        <a-button
          v-permission="['procurement:plan-list-change:updatePlanListChange']"
          :hidden="[10, 15, 20, 25, 30, 35].includes(record.changeStatus)"
          type="text"
          @click="compile(record)"
        >
          编辑
        </a-button>
        <a-button
          v-permission="[
            'procurement:plan-list-change:deletePlanListChangeByIds',
          ]"
          :hidden="[10, 15, 20, 25, 30, 35].includes(record.changeStatus)"
          type="text"
          status="danger"
          @click="delDate(record)"
          >删除</a-button
        >
        <a-button
          v-permission="[
            'procurement:plan-list-change:batchUpdatePlanListChangeStatus2',
          ]"
          :hidden="[10, 15, 20, 25, 30, 35].includes(record.changeStatus)"
          type="text"
          @click="confirm(record)"
          >确认</a-button
        >
        <a-button
          v-permission="[
            'procurement:plan-list-change:batchUpdatePlanListChangeStatus3',
          ]"
          :hidden="[0, 5, 15, 20, 25, 30, 35].includes(record.changeStatus)"
          type="text"
          @click="SubmitExamine(record)"
          >提交审批</a-button
        >
        <a-button
          v-permission="[
            'procurement:plan-list-change:batchUpdatePlanListChangeStatus',
          ]"
          :hidden="[0, 5, 15, 20, 25, 30, 35].includes(record.changeStatus)"
          type="text"
          @click="send(record)"
          >退回</a-button
        >
      </template>
    </query-page>
    <a-modal
      :visible="visibleSend"
      title="退回"
      :on-before-ok="handleSend"
      @cancel="handleCancels"
    >
      <a-form ref="formRefs" :model="sendForm" :rules="rules" auto-label-width>
        <a-form-item
          field="sureReturnCause"
          label="确认退回原因"
          validate-trigger="blur"
        >
          <a-space direction="vertical" size="large" fill>
            <a-textarea
              v-model="sendForm.sureReturnCause"
              style="width: 300px"
              placeholder="请输入确认退回原因"
              :max-length="1000"
              allow-clear
              show-word-limit
            />
          </a-space>
        </a-form-item>
      </a-form>
    </a-modal>
    <editModal
      ref="moduleRef"
      v-model:visible1="demoDialogRef1"
      title="Hello from MyModal"
      :selection="selection"
      @submit="handleSubmit"
    />

    <!-- 采购计划管理 采购计划变更 新增 -->
    <planAlterationReceiveAddPage
      v-if="showModal"
      v-model:show-modal="showModal"
      @refresh="refresh"
    />
    <!-- 采购计划管理 采计划变更 提交审批 -->
    <!-- <planAlterationReceiveSubmitExamine v-if="showModal">
    </planAlterationReceiveSubmitExamine> -->
  </div>
</template>

<script lang="ts" setup>
  import { Message } from '@arco-design/web-vue';
  import { ref, reactive, onMounted } from 'vue';
  // import { useRouter } from 'vue-router';
  import queryPage from '@/common/components/query-page/index.vue';
  import editModal from '@/views/purchase-plan/components/editmodal.vue';
  import {
    formRenderConfig,
    formComponentConfig,
  } from '@/views/purchase-plan/components/formComp/baseFormConfigReceive';
  import {
    tableRenderConfig,
    tableComponentConfig,
  } from '@/views/purchase-plan/components/tableComp/baseTableConfigAlteration';
  import useModal from '@/common/hooks/modal';
  import planAlterationReceiveAddPage from '@/views/purchase-plan/plan-alteration-receive-addPage/index.vue';
  // import planAlterationReceiveSubmitExamine from '@/views/purchase-plan/plan-alteration-receive-submitExamine/index.vue';
  import modalPromise from '@/common/utils/modal-promise';
  import { hasDataAndBack } from '@/common/utils/index';
  import {
    selectPlanListChangeByPage,
    deletePlanListChangeByIds,
    batchUpdatePlanListChangeStatus,
  } from '@/api/purchase-plan/planAuthorized';

  const demoDialogRef1 = ref('');
  const moduleRef = ref();
  const selectedKeys = ref([]);
  const isLoading = ref(true);
  const renderData = ref<any[]>([]);
  const total = ref(0);
  const selection = ref<any[]>([]);
  const sendForm = ref({
    sureReturnCause: '',
    id: '',
  });
  const rules = ref({
    sureReturnCause: [{ required: true, message: '确认退回原因必输' }],
  });
  const queryPageRef = ref();

  //  渲染检索项
  const formRenderKeys = ref<any>([]);
  const formInfo = () => {
    const obj = ref(formRenderConfig);
    formRenderKeys.value = Object.keys(obj.value);
    console.log(Object.keys(obj.value), '1111');
  };
  formInfo();
  // 当前表格要渲染哪些值
  const tableRenderKeys = ref<any[]>([]);
  const tableInfo = () => {
    const obj = ref(tableRenderConfig);
    tableRenderKeys.value = Object.keys(obj.value);
    console.log(Object.keys(obj.value), '1111');
  };
  tableInfo();
  // 新增弹框的事件
  const { showModal, openModal } = useModal();
  // 新增按钮
  const newlyIncreased = () => {
    openModal();
  };

  // 表单选中的数据
  let selectList = reactive<string[]>([]);
  const selectionChange = (val: string[]) => {
    selectList = val;
    console.log('selectedKeys', val);
    selection.value = renderData.value.filter((item) => {
      console.log(item, 'item++++++++++++');
      return val.includes(item.id);
    });
    console.log(selection, 'selectionChange');
  };
  const getData = async (queryInfo: object) => {
    renderData.value = [];
    isLoading.value = true;
    console.log('queryInfo', queryInfo);

    const params = {
      pageNo: 1,
      pageSize: 10,
    };
    try {
      const res = (await selectPlanListChangeByPage({
        ...params,
        ...queryInfo,
      })) as any;
      console.log(res, 'res+++++++++++++');
      if (res.code === 200) {
        total.value = res.data.total;
        renderData.value = res.data.list;
        console.log(renderData, 'renderDatarenderData');
        refreshNumData(renderData.value, total.value);
      }
    } finally {
      isLoading.value = false;
    }
  };
  // 列表 删除回退的问题
  const refreshNumData = (list: any[], tNum: any) => {
    if (hasDataAndBack(list, tNum, queryPageRef.value?.getStatus().pageNo)) {
      queryPageRef.value?.setCurrent(queryPageRef.value.getStatus().pageNo - 1);
      getData(queryPageRef.value.getStatus());
    }
  };
  const refresh = () => {
    showModal.value = false;
    getData();
  };
  // 编辑按钮
  const compile = (record: any) => {
    moduleRef.value.open();
    moduleRef.value.init(record);
  };
  const handleSubmit = () => {
    console.log('编辑');
  };
  // 删除按钮
  const visibleDelDate = ref(false);
  const delDate = async (record: any) => {
    try {
      await modalPromise.info({
        title: '提示',
        content: '您确定要删除当前所选的数据？',
        hideCancel: false,
        onOk: async () => {
          await handleOkDelDate(record);
        },
      });
    } catch {
      return;
    }
    await handleOkDelDate(record);
  };
  const handleOkDelDate = async (record: any) => {
    const arrList = [];
    const params = {};
    selection.value.forEach((k) => {
      arrList.push(k.id);
    });
    params.idList = record.id ? [record.id] : arrList;
    try {
      const res = (await deletePlanListChangeByIds(params)) as any;
      console.log(res, 'res+刪除');
      if (res.code === 200) {
        getData();
        selectedKeys.value = [];
        Message.success({
          content: '删除成功!',
        });
      }
    } finally {
      isLoading.value = false;
    }
    visibleDelDate.value = false;
  };

  // 确认按钮
  const visibleConfirm = ref(false);
  const confirm = async (record: any) => {
    visibleConfirm.value = true;
    console.log('selectList', selectList, visibleConfirm);

    try {
      await modalPromise.info({
        title: '提示',
        content: '您确定要确认当前所选的数据？',
        hideCancel: false,
      });
    } catch {
      return;
    }
    await handleOkConfirm(record);
  };
  const handleOkConfirm = async (record: any) => {
    visibleConfirm.value = false;
    const arrList = [];
    const params = { newStatus: 10 };
    selection.value.forEach((k) => {
      arrList.push(k.id);
    });
    params.idList = record.id ? [record.id] : arrList;
    try {
      const res = (await batchUpdatePlanListChangeStatus(params)) as any;
      console.log(res, 'res+确认');
      if (res.code === 200) {
        getData();
        selectedKeys.value = [];
        Message.success({
          content: '确认成功!',
        });
      }
    } finally {
      isLoading.value = false;
    }
  };

  // 提交审批
  const visibleSubmitExamine = ref(false);
  const SubmitExamine = async (record: any) => {
    console.log('提交审批');
    visibleSubmitExamine.value = true;
    console.log('selectList', selectList, visibleConfirm);
    try {
      await modalPromise.info({
        title: '提示',
        content: '您确定要提交审批当前所选的数据？',
        hideCancel: false,
      });
    } catch {
      return;
    }
    await handleOkSubmitExamine(record);
  };
  const handleOkSubmitExamine = async (record: any) => {
    console.log(record, 'record提交审批');

    visibleSubmitExamine.value = false;
    const arrList = [];
    const params = { newStatus: 20 };
    selection.value.forEach((k) => {
      console.log(k, 'kkkkkkkkkkkkkkkkkkkkkkkk');
      arrList.push(k.id);
    });
    params.idList = record.id ? [record.id] : arrList;
    try {
      const res = (await batchUpdatePlanListChangeStatus(params)) as any;
      console.log(res, 'res+提交审批成功');
      if (res.code === 200) {
        getData();
        selectedKeys.value = [];
        Message.success({
          content: '提交审批成功!',
        });
      }
    } finally {
      isLoading.value = false;
    }
  };

  // 退回
  const formRefs = ref();
  const visibleSend = ref(false);

  const send = (record: any = {}) => {
    console.log(record, '00000record');
    if (record.id) {
      sendForm.value.id = record.id;
    } else {
      sendForm.value.id = '';
    }
    sendForm.value.sureReturnCause = '';
    visibleSend.value = true;
  };
  const handleSend = async () => {
    console.log(
      sendForm.value.sureReturnCause,
      'sendForm.value.sureReturnCause'
    );

    const verifyStatus = await formRefs.value?.validate();
    let result = true;
    if (verifyStatus) {
      result = false;
    } else {
      try {
        await modalPromise.info({
          title: '提示',
          content: '您确定要退回当前所选的数据？',
          hideCancel: false,
        });
      } catch {
        return true;
      }
      await handleOkSend();
    }

    return result;
  };
  const handleCancels = () => {
    visibleSend.value = false;
  };
  const handleOkSend = async () => {
    visibleSend.value = false;
    const arrList = [];
    const params = { newStatus: 5, cause: sendForm.value.sureReturnCause };
    selection.value.forEach((k) => {
      console.log(k, 'selectionkk');

      arrList.push(k.id);
    });
    params.idList = sendForm.value.id ? [sendForm.value.id] : arrList;
    try {
      const res = (await batchUpdatePlanListChangeStatus(params)) as any;
      console.log(res, 'res+确认');
      if (res.code === 200) {
        getData();
        selectedKeys.value = [];
        Message.success({
          content: '退回成功!',
        });
      }
    } finally {
      isLoading.value = false;
    }
  };

  onMounted(() => {});
</script>

<style lang="less" scoped>
  .plan-alteration-receive-container {
    height: calc(100% - 32px);
    margin: 16px;
    padding: 12px 24px;
    background-color: #fff;
    border-radius: 8px;
  }
</style>
